package com.zhh.shiro;


import com.zhh.common.redis.RedisClient;
import com.zhh.exception.UnauthorizedException;
import com.zhh.jwt.JWTToken;
import com.zhh.jwt.JWTUtil;
import com.zhh.pojo.TbUser;
import com.zhh.service.UserService;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;

import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;


@Service
public class MyRealm extends AuthorizingRealm{

    private static final Logger log= LoggerFactory.getLogger(MyRealm.class);

    @Autowired
    private UserService userService;

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private RedisClient redis;


    public RedisClient getRedis(){
        return redis;
    }

    public JWTUtil getJwtUtil(){
        return jwtUtil;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }
    /**
     * 返回权限信息
     * @param principal
     * @return
     */

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {

        //获取用户名
        String username = principal.toString();
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        //获得授权角色
        authorizationInfo.setRoles(userService.getRoles(username));
        //获得授权权限
        Set<String> ps = userService.getPermissions(username);
        authorizationInfo.setStringPermissions(ps);
        return authorizationInfo;
    }

    /**
     * 先执行登录验证
     * @param auth
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = jwtUtil.getUsername(token);
        if (username == null) {
            throw new AuthenticationException("token invalid");
        }

        TbUser userBean = userService.getUserByname(username);
        if (userBean == null) {
            throw new AuthenticationException("User didn't existed!");
        }

        if (! jwtUtil.verify(token, username, userBean.getPassword())) {
            throw new AuthenticationException("Username or password error");
        }

        return new SimpleAuthenticationInfo(username, token, "my_realm");
    }
}
